//
//  Queue.m
//  OCBase
//
//  Created by 侯伟 on 2019/4/16.
//  Copyright © 2019年 侯伟. All rights reserved.
//

#import "Queue.h"

@implementation Queue


/// 异步执行代码块（主队列执行）
+ (void)asyncMain:(void (^ __nullable)(void))mainTask{
    dispatch_async(dispatch_get_main_queue(), mainTask);
}

/// 异步执行代码块（全局队列执行）
+ (void)asyncGlobal:(void (^ __nullable)(void))globalTask{
    dispatch_async(dispatch_get_global_queue(0, 0), globalTask);
}

/// 异步执行代码块（先全局队列执行，再返回主队列执行）
+(void)asyncGlobal:(id (^ __nullable)(void))globalTask mainTask:(void (^ __nullable)(id obj))mainTask{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id obj = globalTask();
        [Queue asyncMain:^{
            mainTask(obj);
        }];
    });
}

/// 异步执行代码块（自定义队列执行）
+ (void)asyncQueue:(void (^ __nullable)(void))queueTask{
    dispatch_queue_t queue = dispatch_queue_create("com.OCBase.queue", NULL);
    dispatch_async(queue, queueTask);
}

/// 异步执行代码块（先自定义队列执行，再返回主队列执行）
+(void)asyncQueue:(id (^ __nullable)(void))queueTask mainTask:(void (^ __nullable)(id obj))mainTask{
    dispatch_queue_t queue = dispatch_queue_create("com.OCBase.queue", NULL);
    dispatch_async(queue, ^{
        id obj = queueTask();
        [Queue asyncMain:^{
            mainTask(obj);
        }];
    });
}


/// 顺序执行代码块（在主队列中执行）
+ (void)syncMain:(void (^ __nullable)(void))mainTask{
    dispatch_sync(dispatch_get_main_queue(), mainTask);
}

/// 顺序执行代码块（在全局队列执行）
+ (void)syncGlobal:(void (^ __nullable)(void))globalTask{
    dispatch_sync(dispatch_get_global_queue(0, 0), globalTask);
}

/// 顺序执行代码块（先全局队列执行，再返回主队列执行）
+(void)syncGlobal:(id (^ __nullable)(void))globalTask mainTask:(void (^ __nullable)(id obj))mainTask{
    dispatch_sync(dispatch_get_global_queue(0, 0), ^{
        id obj = globalTask();
        if(mainTask){
            [Queue syncMain:^{
                mainTask(obj);
            }];
        }
    });
}

/// 顺序执行代码块（自定义队列执行）
+ (void)syncQueue:(void (^ __nullable)(void))queueTask{
    dispatch_queue_t queue = dispatch_queue_create("com.OCBase.queue", NULL);
    dispatch_sync(queue, queueTask);
}

/// 顺序执行代码块（先自定义队列执行，再返回主队列执行）
+(void)syncQueue:(id (^ __nullable)(void))queueTask mainTask:(void (^ __nullable)(id obj))mainTask{
    dispatch_queue_t queue = dispatch_queue_create("com.OCBase.queue", NULL);
    dispatch_sync(queue, ^{
        id obj = queueTask();
        [Queue syncMain:^{
            mainTask(obj);
        }];
    });
}

//延时s执行
+ (void)delay:(CGFloat)seconds task:(dispatch_block_t)task{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), task);
}


@end
